import smtplib
import random
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText


from core.decorators.open_api import open_api
from core.cache.redis_cache import RedisService


class EmailServie:
    @open_api(name="email.get.code")
    def get_code(self, email_str):
        if not email_str:
            return False

        def get_code(length=6):
            # 生成一个六位数的验证码
            return str(random.randint(10**(length-1), 10**length - 1))

        # 设置发件人和收件人的邮箱地址
        sender_email = "2211986234@qq.com"
        receiver_email = email_str

        # 设置邮件内容
        code = get_code()
        subject = "验证码"
        body = f"本次的验证码为：{code},有效期为3分钟"

        # 创建邮件对象
        msg = MIMEMultipart()
        msg['From'] = sender_email
        msg['To'] = receiver_email
        msg['Subject'] = subject

        # 添加邮件正文
        msg.attach(MIMEText(body, 'plain'))

        # 设置 SMTP 服务器和登录凭据
        smtp_server = "smtp.qq.com"
        username = sender_email
        password = "wkwngpkcgubfdjad"

        # 连接到 SMTP 服务器并发送邮件
        with smtplib.SMTP(smtp_server) as server:
            server.starttls()
            server.login(username, password)
            server.sendmail(sender_email, receiver_email, msg.as_string())
        # 发送成功，存入redis
        RedisService.setStrRedis(f"register:{email_str}", code, 60 * 3)

        return True

    @staticmethod
    def is_right_code(code,email_str):
        return code == RedisService.getStrRedis(f"register:{email_str}")
